/**
* @CopyRight tstudy.com.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.community;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;

import com.loopj.android.http.ResponseHandlerInterface;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.album.Bimp;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.camera.CameraActivity;
import com.tstudy.laoshibang.emojicon.EmojiconEditText;
import com.tstudy.laoshibang.emojicon.EmojiconsFragment;
import com.tstudy.laoshibang.emojicon.emoji.Emojicon;
import com.tstudy.laoshibang.event.SelectPictureEvent;
import com.tstudy.laoshibang.login.NeedLoginFragment;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.mode.response.FileUploadResponse;
import com.tstudy.laoshibang.utils.BitmapUtil;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.greenrobot.event.EventBus;
@SuppressLint("InflateParams")
@EFragment(R.layout.community_publish)
public class CommunityPublishFragment extends NeedLoginFragment{
	final static String TAG = "community_publish";
	public CommunityPublishFragment() {
		super();
	}
	
	@ViewById(R.id.community_publish_root)
	RelativeLayout mRootLayout;
	
	
	@ViewById(R.id.community_publish_content)
	EmojiconEditText mContentExt;
	
	@ViewById(R.id.community_publish_location_layaout)
	RelativeLayout mLocationLayout;
	
	@ViewById(R.id.community_publish_location)
	TextView mLocation;
	
	@ViewById(R.id.community_publish_img_layout)
	RelativeLayout mImgLayout;
	
	@StringRes(R.string.community_publish_add_location)
	String mAddLocationStr;
	
	@ViewById(R.id.community_publish_name)
	RelativeLayout mPublishName;
	@ViewById(R.id.community_publish_header_signature)
	ImageView mPublishHeaderSign;
	@ViewById(R.id.community_publish_header_anonymous)
	ImageView mPublishHeaderAmoyns;
	
	@ViewById(R.id.community_publish_emoji)
	ImageView mEmojiAction;
	
	@ViewById(R.id.community_publish_emoji_layout)
	RelativeLayout mEmojiLayout;
	
	@ViewById(R.id.community_publish_bottom_layout)
	LinearLayout mBottomLayout;
	
	boolean mIsFirstLoad = true;
	boolean mIsLocation = false;
	Handler mHandler;
	LayoutInflater mInflater;
	int mCurrentPosition = 0;
	int bottomHeight = (int)BaseApplication.mContext.getResources().getDimension(R.dimen.camera_bottom_height);
	String mFilePath;
	String mUpToken;
	List <String> filePathList = new ArrayList<String>();
	List <String> fileThumePathList = new ArrayList<String>();
//	List<Idxe> mIdxes = new ArrayList<Idxe>();
	String[] qnIds;
	int successSize;
	int mHeightDifference;
	boolean mkeyBordShow;
	
	public static void add(int containerViewId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,CommunityPublishFragment_.class.getName(),args);
		((BaseActivity)BaseApplication.mCurrentActivity).add(containerViewId,fragment,TAG);	
	
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		EventBus.getDefault().register(this);
		super.onCreate(savedInstanceState);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	RelativeLayout.LayoutParams headerLp;
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
//			headerLp = (RelativeLayout.LayoutParams) mPublishHeader.getLayoutParams();
			mContentExt.getLayoutParams().height = BaseApplication.mScreenWidth/2;
			mPublishHeaderSign.setVisibility(View.VISIBLE);
			mPublishHeaderAmoyns.setVisibility(View.GONE);
			mRootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
				@Override
				public void onGlobalLayout() {
					Rect r = new Rect();
					mRootLayout.getWindowVisibleDisplayFrame(r);
					int screenHeight = mRootLayout.getRootView().getHeight();
					mHeightDifference = screenHeight - (r.bottom - r.top);
					if (mHeightDifference > BaseApplication.mStatusBarHeight) {
//						LogUtil.d("--screenHeight==" + screenHeight + ",r.bottom==" + r.bottom + ",r.top==" + r.top + ",softheight==" + mHeightDifference );
						mkeyBordShow = true;
						mEmojiAction.setImageResource(R.drawable.expression);
						mEmojiLayout.setVisibility(View.GONE);
//						mBottomLayout.scrollTo(0, BaseApplication.mScreenHeight-mHeightDifference);
					}else{
//						LogUtil.d("mHeightDifference==" + mHeightDifference );
//						mRootLayout.scrollTo(0, 0);
//						mBottomLayout.scrollTo(0, BaseApplication.mScreenHeight-BaseApplication.mStatusBarHeight);
						if (mkeyBordShow) {
							mEmojiAction.setImageResource(R.drawable.keyboard);
						}
						mkeyBordShow = false;
					}
				}
			});
		}
	}
	final int COLUMN_SIZE = 3;
	int photoMargin = CommonUtil.dip2px(9);
	int layoutMargin = CommonUtil.dip2px(6);
	int mBigImgWidth = BaseApplication.mScreenWidth - CommonUtil.dip2px(30);
	int mBigImgHeigh = mBigImgWidth*2/3;
	int  mImageWidth = (BaseApplication.mScreenWidth -photoMargin*4-layoutMargin*2)/COLUMN_SIZE;
	int loveMargin = CommonUtil.dip2px(10);
	int mImageHeight = mImageWidth*2/3;
	public void fillImgLayout(final RelativeLayout layout) {
		layout.removeAllViews();
		int size = filePathList.size();
		for (int i = 0; i < size; i++) {
			ImageView imgView = new ImageView(BaseApplication.mContext);
			ImageView deleteIcon = new ImageView(BaseApplication.mContext);
			imgView.setId(i + 1);
			imgView.setScaleType(ScaleType.FIT_XY);
			RelativeLayout.LayoutParams imgLp = new RelativeLayout.LayoutParams(mImageWidth, mImageHeight);
			if (size ==1) {
				imgLp.width = mBigImgWidth;
				imgLp.height = mBigImgHeigh;
			}
			RelativeLayout.LayoutParams loveLp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
			loveLp.setMargins(0, loveMargin, loveMargin, 0);
			loveLp.addRule(RelativeLayout.ALIGN_TOP,imgView.getId());
			loveLp.addRule(RelativeLayout.ALIGN_RIGHT,imgView.getId());
			deleteIcon.setImageResource(R.drawable.icon_delete);
			int rowIndex = i/COLUMN_SIZE;
			int columnIndex = i%COLUMN_SIZE;
			if (rowIndex != 0) {
				imgLp.addRule(RelativeLayout.BELOW,i-COLUMN_SIZE+1);
			}
			if (columnIndex != 0) {
				imgLp.setMargins(0, 0,photoMargin, photoMargin);
				imgLp.addRule(RelativeLayout.RIGHT_OF, i);
			}else{
				imgLp.setMargins(photoMargin, 0, photoMargin, photoMargin);
			}
			Bitmap bitmap = BitmapFactory.decodeFile(filePathList.get(i));
			imgView.setImageBitmap(bitmap);
			layout.addView(imgView, imgLp);
			layout.addView(deleteIcon,loveLp);
			final int position = i	;
			deleteIcon.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					filePathList.remove(position);
					fillImgLayout(layout);
				}
			});
		}
	}
	
	/**
//	 * 获取上传token
//	 */
//	public void getToken(){
//		 BaseJsonHandler<QiniuTokenResponse> response = new BaseJsonHandler<QiniuTokenResponse>() {
//			@Override
//			public void onStart() {
//				// TODO Auto-generated method stub
////				showProgress("", "", 0);
//				super.onStart();
//			}
//			@Override
//			public void onSuccess(int statusCode, Header[] headers,
//					String rawJsonResponse, QiniuTokenResponse response) {
//				super.onSuccess(statusCode, headers, rawJsonResponse, response);
//				if (CommonUtil.responseSuccess(response)) {
//					mUpToken = response.getUpToken();
//				}else {
//                    BaseApplication.showToast(response.getErrMsg());
//                }
//			}
//			@Override
//			protected QiniuTokenResponse parseResponse(String rawJsonData, boolean isFailure)
//					throws Throwable {
//				return mGson.fromJson(rawJsonData,QiniuTokenResponse.class);
//			}
//			
//		};
//		
//		HttpManager.getInstance().getQiniuToken(BaseApplication.mUserNo, response);
//		
//	}
//	
//	/**
//	 * 上传图片至七牛服务器
//	 */
//	public void uploadImg(){
//		UploadManager uploadManager = new UploadManager();
//		String data = mFilePath;
//		final String keyParam = System.currentTimeMillis()+".jpg";
//		uploadManager.put(data, keyParam, mUpToken,
//		new UpCompletionHandler() {
//		    @Override
//		    public void complete(String key, ResponseInfo info, JSONObject response) {
//		        LogUtil.d("qiniu key==" + key + ",info=" + info + ",response== " + response);
//		        if (keyParam.equals(key) && response != null && info.isOK() == true) {
//		        	communityPublish();
//				}
//		        
//		    }
//		}, null);
//	}
	
	public void viewAniamtor(View view){
	       AnimatorSet animatorSet = new AnimatorSet();  
	       ObjectAnimator bigX = ObjectAnimator.ofFloat(view, "x", 0);  
	       bigX.setRepeatMode(Animation.REVERSE);  
	       bigX.setDuration(200);  
	       
	       ObjectAnimator bigY = ObjectAnimator.ofFloat(view, "y",BaseApplication.mScreenHeight,0);  
	       bigY.setRepeatMode(Animation.REVERSE);  
	       bigY.setDuration(200);  
	       animatorSet.playTogether(bigY);
	       animatorSet.start();  
	   }  
	
	public void showEmojiLayout(){
		if (mHeightDifference> BaseApplication.mStatusBarHeight) {
			mEmojiLayout.getLayoutParams().height = mHeightDifference-BaseApplication.mStatusBarHeight;
		}
		if (mEmojiLayout.getVisibility() == View.VISIBLE) {
			mEmojiAction.setImageResource(R.drawable.expression);
			mEmojiLayout.setVisibility(View.GONE);
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					showSoftKeyBoard(mContentExt, true);
				}
			}, 100);
		}else{
			mEmojiAction.setImageResource(R.drawable.keyboard);
			showSoftKeyBoard(mContentExt, false);
//			mEmojiLayout.setVisibility(View.VISIBLE);
//			viewAniamtor(mEmojiLayout);
			mHandler.postDelayed(new Runnable() {
				public void run() {
					mEmojiLayout.setVisibility(View.VISIBLE);
					mEmojiLayout.startAnimation(AnimationUtils.loadAnimation(BaseApplication.mContext, R.anim.slide_in_from_bottom));
//					mEmojiLayout.getLayoutParams().height = CommonUtil.dip2px(260);
				}
			},100);
			getChildFragmentManager()
	        .beginTransaction()
	        .replace(R.id.community_publish_emoji_layout, EmojiconsFragment.newInstance(false))
	        .commit();
		}
	}
	
	/**
	 * 文件上传
	 * @param filePath
	 */
	public void fileUpload(){
		ResponseHandlerInterface response = new BaseJsonHandler<FileUploadResponse>() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, FileUploadResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					setCount(response.data.qnPicId);
//					qnIds[successSize] = response.data.qnPicId;
//					successSize++;
//					if (successSize == filePathList.size()) {
//						communityPublish();
//					}
				} else {
                    BaseApplication.showToast(response.getErrMsg());
                }
			}
			@Override
			public void onFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
				hideLoadingProgressDialog();
				BaseApplication.showToast("上传图片失败:" + statusCode);
				super.onFailure(statusCode, headers, responseBytes, throwable);
			}
			@Override
			protected FileUploadResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,FileUploadResponse.class);
			}
		};
		int size = filePathList.size();
		qnIds = new String[size];
		for (int i = 0; i < size; i++) {
			HttpManager.getInstance().fileUpload(filePathList.get(i), response);
		}
	}
	
	public void setCount(String path){
		qnIds[successSize] = path;
		successSize++;
		if (successSize == filePathList.size()) {
			communityPublish();
		}
	}

	private void communityPublish(){
		if (mIsLoading) {
			return ;
		}
		mIsLoading = true;
		BaseJsonHandler<BaseResponse> response = new BaseJsonHandler<BaseResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					getActivity().finish();
					EventBus.getDefault().post("");
				}else{
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					BaseResponse errorResponse) {
					afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().createCommunity(BaseApplication.mUserNo,mContentExt.getText().toString(),isAnonymous?1:0,mIsLocation?BaseApplication.mCurrentAddress:null, qnIds, response);
		
	}
	@Click({R.id.community_publish_emoji,R.id.community_publish_action,R.id.community_publish_back,R.id.community_publish_location,R.id.community_publish_location_remove,R.id.community_publish_album,R.id.community_publish_camera,R.id.community_publish_header_anonymous,R.id.community_publish_header_signature,R.id.community_publish_name})
	public void actionClick(View view){
		switch (view.getId()) {
		case R.id.community_publish_back:
			backAction(mFragmentId);
			getActivity().finish();
			break;
		case R.id.community_publish_name:
			setAnonymous();
			break;
		case R.id.community_publish_header_anonymous:
			setAnonymous();
			break;
		case R.id.community_publish_header_signature:
			setAnonymous();
			break;
		case R.id.community_publish_action:
			String content = BaseApplication.mContext.getString(R.string.community_publishing);
			showProgressDialog("",content,0);
			if (filePathList != null && filePathList.size() > 0) {
				fileUpload();
			}else{
				communityPublish();
			}
			break;
		case R.id.community_publish_location:
			if (BaseApplication.mCurrentAddress != null) {
				mIsLocation = true;
				mLocation.setText(BaseApplication.mCurrentAddress.provinceName + " " + BaseApplication.mCurrentAddress.cityName);
			}
			
			break;
		case R.id.community_publish_location_remove:
			mIsLocation = false;
			mLocation.setText(mAddLocationStr);
			break;
		case R.id.community_publish_album:
			if (filePathList.size() == 9) {
				BaseApplication.showToast(R.string.max_picture_toast);
			}else{
//				CameraActivity.show(false, false);
				AlbumFragment.add(mFragmentId);
			}
			break;
		case R.id.community_publish_camera:
			if (filePathList.size() == 9) {
				BaseApplication.showToast(R.string.max_picture_toast);
			}else{
				CameraActivity.show(false, true);
			}
			break;
		case R.id.community_publish_emoji:
			showEmojiLayout();
			
			break;
		default:
			break;
		}
		if (isShowInput()) {
			if (mkeyBordShow) {
				showSoftKeyBoard(mContentExt, false);
			}else{
				mEmojiAction.setImageResource(R.drawable.expression);
				mEmojiLayout.setVisibility(View.GONE);
			}
		}
	}
	public boolean isAnonymous = false;
	public void setAnonymous(){
		isAnonymous = !isAnonymous;
		mPublishName.setSelected(isAnonymous);
		if (isAnonymous) {
			mPublishHeaderAmoyns.setVisibility(View.VISIBLE);
			mPublishHeaderSign.setVisibility(View.GONE);
		}else{
			mPublishHeaderAmoyns.setVisibility(View.GONE);
			mPublishHeaderSign.setVisibility(View.VISIBLE);
		}
	}

	public void onEventMainThread(SelectPictureEvent selectPictureEvent) {
//		 	Idxe idxe = new Idxe();
//		 	idxe.imgIdxName = filePath;
//		 	idxe.type = CONSTANT.MEDIA_TYPE_PICTURE;
//	        mIdxes.add(idxe);
		if (selectPictureEvent != null && selectPictureEvent.filePaths != null) {
			filePathList.clear();
			int size = selectPictureEvent.filePaths.size();
			for (int i = 0; i < size; i++) {
				Bitmap bitmap = BitmapUtil.getThumbImage(selectPictureEvent.filePaths.get(i),BaseApplication.mScreenWidth);
				final String filePath = CommonUtil.saveImage(CommonUtil.getUploadPicturePath(),bitmap);
				filePathList.add(filePath);
			}
		}else{
			filePathList.add(selectPictureEvent.filePath);
		}
		fillImgLayout(mImgLayout);
//	     Bimp.drr.clear();
	}

	public void afterLoading(){
		mIsLoading = false;
		hideLoadingProgressDialog();
	}
	
	public void clear() {
		mEmojiLayout.setVisibility(View.GONE);
		showSoftKeyBoard(mContentExt, false);
		Bimp.bmp.clear();
		Bimp.drr.clear();
	}
	
	public boolean isShowInput(){
		return mkeyBordShow || mEmojiLayout.getVisibility() == View.VISIBLE;
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
		}
	}
	
	public void onEmojiconBackspaceClicked(View v) {
		EmojiconsFragment.backspace(mContentExt);
		
	}
	public void onEmojiconClicked(Emojicon emojicon) {
		EmojiconsFragment.input(mContentExt, emojicon);
		
	}
	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	};
	
}
